package com.ykt.controller;

import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.ykt.model.CameraShop;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@ControllerBind(controllerKey="/cameraShop")
public class CameraShopController extends BaseController<CameraShop> {

	public CameraShopController() {
		super(CameraShop.class);
	}
	
	public void findCamera() {
		Integer shopId = getParaToInt("shopId", -1);
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("s.id", shopId.toString());
		
		int page = getParaToInt("page", 1);
        int rows = this.getParaToInt("rows", 20);
        try {
            Page<CameraShop> date = modelClass.newInstance().pageFindModel(page, rows, paramMap);
            rendDataGrid(date);
        } catch (Exception e) {
            log.error(e);
            rendJson(false, e.getMessage());
        }
	}
	
	public void savaCamera(){
		String shopId = this.getPara("shopId");
		String cameraId = this.getPara("cameraId");
		
		String sql = "SELECT * FROM camera_shop c WHERE c.camera_id = " + cameraId + " AND c.shop_id = " + shopId;
		CameraShop shop = null;
		shop = CameraShop.dao.findFirst(sql);
		
		String msg = "此摄像头已经存在！";
		Integer id = null;
		if (shop == null) {
			shop = new CameraShop();
			shop.set("shop_id", shopId);
			shop.set("camera_id", cameraId);
			shop.save();
			msg = "保存成功！";
			id = shop.getInt("id");
		}
		rendJson(true, msg, id, new Random().nextLong());
	}
	
	public void deleteCamera(){
		String id = this.getPara("id");
		CameraShop.dao.deleteById(id);
		String msg = "删除成功！";
		id = null;
		rendJson(true, msg, id, new Random().nextLong());
	}

}
